package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.BannerEntity;
import com.example.HaiDLaobackend.service.BannerService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/banners")
public class BannerController {

	private final BannerService bannerService;

	public BannerController(BannerService bannerService) {
		this.bannerService = bannerService;
	}

	@GetMapping
	public ApiResponse<List<BannerEntity>> list() {
		List<BannerEntity> banners = bannerService.list(new LambdaQueryWrapper<BannerEntity>()
			.eq(BannerEntity::getStatus, 1)
			.orderByAsc(BannerEntity::getSortOrder));
		return ApiResponse.ok(banners);
	}

	@PostMapping("/upload")
	public ApiResponse<String> uploadImage(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return ApiResponse.error("文件为空");
		}
		
		try {
			// 获取项目根目录（pom文件所在目录）
			String projectRoot = System.getProperty("user.dir");
			File uploadDir = new File(projectRoot, "uploads/banner");
			if (!uploadDir.exists()) {
				uploadDir.mkdirs();
			}
			
			// 生成唯一文件名
			String originalFilename = file.getOriginalFilename();
			String extension = originalFilename != null && originalFilename.contains(".") 
				? originalFilename.substring(originalFilename.lastIndexOf(".")) 
				: "";
			String filename = UUID.randomUUID().toString() + extension;
			File destFile = new File(uploadDir, filename);
			
			// 保存文件
			file.transferTo(destFile);
			
			// 返回相对路径
			return ApiResponse.ok("/uploads/banner/" + filename);
		} catch (IOException e) {
			return ApiResponse.error("文件上传失败: " + e.getMessage());
		}
	}
}

